﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using personalplaner.common.mvvm;
using System.Windows;
using personalplaner.business.stamm;
using System.Collections.ObjectModel;
using personalplaner.servicemodel.dataaccess;
using personalplaner.common.mvvm.common;
using personalplaner.gui.mainview.views;
using personalplaner.common;
using personalplaner.business.dienstplan;
using personalplaner.common.mvvm.mediator;
using personalplaner.gui.common;
using personalplaner.common.plugins;
using personalplaner.gui.plugins.dienstplan.views;
using personalplaner.gui.plugins.about;
using personalplaner.gui.plugins;
using System.Windows.Media;
using System.Reflection;
using System.IO;
using System.Windows.Media.Imaging;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using personalplaner.business;

namespace personalplaner.gui.mainview.viewmodels
{
    public class ViewControlerViewModel : BaseViewModel, IViewControler
	{
		CompositionContainer _container;

        //public IEnumerable<Lazy<IPlugin, IPluginMetadata>> Plugins
        /// <summary>
        /// Enumeration containing all loaded pluginsEnumeration containing all loaded plugins
        /// </summary>
		[ImportMany]
		public IEnumerable<IPlugin> Plugins
		{
			get;
			set;
		}



		public ViewControlerViewModel(DependencyObject parent)
            : base(parent)
        {
            ServiceLocator.RegisterGlobalService<IViewControler>(this);

            Elements = new ObservableCollection<Plugin>();

            if (Designer.IsDesignMode)
                return;

			var plan = new Plugin
			{
				View = new DienstPlanPlugin(),
				Name = "Plan",
				Description = "Show and edit the plan"
			};
			plan.Icon = LoadIcon(plan.GetType(), "resources\\images\\Plan.png");
			Elements.Add(plan);

			if (Compose())
			{
				//foreach (Lazy<IPlugin, IPluginMetadata> m in Plugins)
				//{
				//    var plugin = new Plugin
				//    {
				//        View = m.Value as FrameworkElement,
				//        Name = m.Metadata.Name,
				//        Description = m.Metadata.Description
				//    };
				//    plugin.Icon = LoadIcon(plugin.View.GetType(), m.Metadata.IconPath);
				//    Elements.Add(plugin);
				//}
				foreach (var m in Plugins)
				{
					var plugin = new Plugin
					{
						View = m as FrameworkElement,
						Name = m.PluginName,
						Description = m.Description
					};
					plugin.Icon = LoadIcon(plugin.View.GetType(), m.IconPath);
					Elements.Add(plugin);
				}
			}

			var about = new Plugin
			{
				View = new AboutView(),
				Name = "About",
				Description = "About wickedflame"
			};
			about.Icon = LoadIcon(about.GetType(), "resources\\images\\Personalplaner.png");
			Elements.Add(about);
			
        }

		/// <summary>
		/// Use MEF to Compose all all objects of the exported type <see cref="IPlugin"/>
		/// </summary>
		/// <returns></returns>
		private bool Compose()
		{
            if (!Directory.Exists("plugins"))
                return false;

			var catalog = new AggregateCatalog();
			catalog.Catalogs.Add(new DirectoryCatalog("plugins"));

			_container = new CompositionContainer(catalog);

			try
			{
				_container.ComposeParts(this);
			}
			catch (Exception)
			{
				return false;
			}

			return true;
		}

    	public void SelectControl(UIElement control)
        {
            SelectedControl = control;
        }

        UIElement _selectedControl;
        public UIElement SelectedControl
        {
            get
            {
                return _selectedControl;
            }
            set
            {
                _selectedControl = value;
                RaisePropertyChanged("SelectedControl");

				Mediator.NotifyColleagues<UIElement>("ViewControlerSelectionChanged", value);
            }
        }

		IList<Plugin> _elemtents;
		public IList<Plugin> Elements
        {
            get
            {
                return _elemtents;
            }
            set
            {
                _elemtents = value;
                RaisePropertyChanged("Elements");
            }
        }

		private ImageSource LoadIcon(Type typ, string icon, string iconNamespace = null)
        {
            var asm = Assembly.GetAssembly(typ);
			if (string.IsNullOrEmpty(iconNamespace))
				iconNamespace = typ.Namespace;
			string iconString = iconNamespace + '.' + icon.Replace('\\', '.');
            Stream myStream = asm.GetManifestResourceStream(iconString);

            if (myStream == null)
            {
                iconString = typ.Name + '.' + icon.Replace('\\', '.');
                myStream = asm.GetManifestResourceStream(iconString);
            }

            if (myStream == null)
            {
                iconString = "Kaxaml.Images.package.png";
                myStream = asm.GetManifestResourceStream(iconString);
            }

            if (myStream != null)
            {
                var bitmapDecoder = new PngBitmapDecoder(myStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                if (bitmapDecoder.Frames[0] != null && bitmapDecoder.Frames[0] is ImageSource)
                {
                    return bitmapDecoder.Frames[0];
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        #region Implementation

        public override void Loaded()
        {
            var mw = GetService<IMainWindowDisplayContainer>();
            mw.IsWaitVisible = false;
        }

        #endregion

	}
}
